<?php

!defined('IN_NOVA') && exit('Access Denied!');

class Log {

	private $log;

	private $trace_enable;

	function __construct() {
		$this->log = array();
		$this->trace_enable = TRUE;

		// 这些级别的日志会被写入日志文件
		if( !defined( 'LOG_LEVEL' ) ) {
			define( 'LOG_LEVEL', E_ERROR|E_WARNING|E_USER_ERROR|E_USER_WARNING|E_RECOVERABLE_ERROR );
		}
	}

	// 添加一条日志
	public function add( $message, $level ) {
		if( defined( 'APP_LOG' ) && APP_LOG === TRUE && check_error_level( LOG_LEVEL, $level ) ) {
			$this->write( $message, $level );
		}
		$this->log[] = array( 'MES' => $message, 'TEM' => PHP_TIME, 'LEV' => $level );
	}

	// 返回应用运行过程中的跟踪信息
	public function trace( $mark = FALSE ) {
		global $request,$cache,$_NOVA,$_LANGUAGE;
		if( !isset( $request ) || !isset( $cache ) || !isset( $_NOVA ) ) return '';
		if( $this->trace_enable || $mark ) {
			$content = '<div style="height:400px; width:95%; border: 2px solid #cfcfcf; overflow:auto; padding:5px; text-align:left;">';
			$content .= "<b>以下是应用运行过程中的跟踪信息：</b><br /><br />";
			$content .= '<b>当前页面：</b>' . $request->get( 'REQUEST_URI', 'S' ) . '<br />';
			$content .= '<b>请求方法：</b>' . $request->get( 'REQUEST_METHOD', 'S' ) . '<br />';
			$content .= '<b>通信协议：</b>' . $request->get( 'SERVER_PROTOCOL', 'S' ) . '<br />';
			$content .= '<b>请求时间：</b>' . date( 'Y-m-d H:i:s', $request->get( 'REQUEST_TIME', 'S' )) . '<br />';
			$content .= '<b>用户代理：</b>' . $request->get( 'HTTP_USER_AGENT', 'S' ) . '<br />';
			$content .= '<b>会话 I D：</b>' . session_id() . '<br /><br />';
			$content .= '<b>日志记录：</b><br /><br />';

			foreach( $this->log as $log ) {
				$content .= '[' . date( 'Y-m-d H:i:s', $log['TEM'] ) . ' ] [' . $log['LEV'] . '] ' . $log['MES'] . '<br />';
			}
			$content .= '<br /><b>全局变量：</b><br /><br />'/* . dump( $_NOVA, FALSE ) . dump( $_LANGUAGE, FALSE )*/ . '$_GET<br />' . dump( $_GET, FALSE ) . '$_POST<br />' . dump( $_POST, FALSE ) . '$_COOKIE<br />' . dump( $_COOKIE, FALSE )/* . dump( $_SERVER, FALSE )*/;
			//$content .= '<br /><b>缓存信息：</b><br /><br />' . dump( $cache->get_all(), FALSE );
			$files =  get_included_files();
			$content .= '<br /><b>加载文件：</b><br />' . dump( $files, FALSE );//str_replace("\n",'<br />',substr(substr(print_r($files,true),7),0,-2));
			$content .= '</div>';
			$this->trace_enable = FALSE;
		} else {
			$content = '';
		}

		return $content;
	}

	private function write( $message, $level ) {
		if( !is_file( NOVA_LOG . date( 'Y-m-d' ) . '.php' ) ) {
			file_put_contents( NOVA_LOG . date( 'Y-m-d' ) . '.php' , "<?php exit('Access Denied!'); ?>\n" );
		}
		$content = '[' . Request::get_ip() . '] [' . date( 'Y-m-d H:i:s' ) . '] [' . $level . '] ' . $message . "\n";
		file_put_contents( NOVA_LOG . date( 'Y-m-d' ) . '.php' , $content, FILE_APPEND );
	}
}
?>
